package com.dapeis.api.controller.collocation.impl;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ag.core.exception.InvalidParamException;
import com.ag.core.exception.InvalidVerifyCodeException;
import com.ag.core.exception.SysTipsException;
import com.ag.module.common.api.service.SMSService;
import com.ag.module.common.web.TagUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.api.controller.RestController;
import com.dapeis.api.controller.collocation.ILoginCotroller;
import com.dapeis.api.utils.ApiTokenUtils;
import com.dapeis.api.utils.StylistConfig;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Collocation;
import com.dapeis.domain.ext.CollocationExt;
import com.dapeis.service.COSFileService;
import com.dapeis.service.CollocationInformationService;
import com.dapeis.service.CollocationService;
import com.dapeis.service.QRCodeService;
import com.dapeis.service.TIMService;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * @author 作者 E-mail:
 * @version 创建时间：2017年4月20日 下午4:51:27 类说明
 */

@Controller
@RequestMapping("/dps")
public class LoginControllerImpl extends RestController implements
	ILoginCotroller {
    @Resource
    CollocationService collocationService;
    @Resource
    CollocationInformationService inforService;
    @Resource
    SMSService smsService;
    @Resource
    QRCodeService qrCodeService;
    @Resource
    TIMService timService;

    @Override
    public JsonElement login(String contact, String verifyCode,
	    String deviceId, HttpServletRequest request) {
	Collocation sessionCollocation = getThreadLocalCollocation();
	if (sessionCollocation != null) {
	    // 已经是登陆的情况
	    throw new SysTipsException("你已经登陆.");
	}
	if (StringUtils.isBlank(contact) || StringUtils.isBlank(verifyCode)) {
	    throw new InvalidParamException();
	}
	// ! 验证,否为不验证
	if (!smsService
		.checkVerifyCode(StylistConstants.ChannelType.DPS.APP_LOGIN,
			contact, verifyCode)) {
	    throw new InvalidVerifyCodeException();
	}

	Collocation collocation = collocationService
		.getCollocationByContact(contact);
	if (null == collocation) {
	    // 新用户注册
	    collocation = new Collocation();
	    collocation.setContact(contact);
	    String nickName = "";
	    try {
		nickName = contact.substring(0, 3)
			+ "****"
			+ contact.substring(contact.length() - 3,
				contact.length());
	    } catch (Exception e) {
		logger.error("根据手机号生产realName失败:" + e.getLocalizedMessage());
	    }
	    collocation.setNickName(nickName);
	    collocation.setAuditState(StylistConstants.Audit.NO_SUBMIT);
	    collocationService.insert(collocation);
	    boolean result = timService.importAccount(collocation);
	    logger.info("register QTIM CollocationId +" + collocation.getId()
		    + ",Result:" + result);
	    String qrUrl = qrCodeService.createCollocationQRCode(collocation,
		    request);
	    if (StringUtils.isNotBlank(qrUrl)) {
		collocation.setQrCodeUrl(qrUrl);
		collocationService.updateByPrimaryKeySelective(collocation);
	    }

	}
	collocationService.checkCollocationVaild(collocation);

	String ip = TagUtils.getRemoteIp(request);
	String deviceType = request.getParameter("deviceType");
	String deviceName = request.getParameter("deviceName");
	String appVersion = request.getParameter("appVersion");

	collocationService.doLoginRecord(collocation, ip, deviceType,
		deviceName, appVersion);
	String token = ApiTokenUtils.generateTokenAndSaveRedis(request,
		collocation.getId(), ApiTokenUtils.COLLOCATION_REDIS_PRE_KEY,
		StylistConfig.collocationTokenKey, deviceId);
	smsService.setVerifyCodeVaild(
		StylistConstants.ChannelType.DPS.APP_LOGIN, contact);
	CollocationExt collocationExt = collocationService
		.getCollocationExtMapper().selectByPrimaryKey(
			collocation.getId());

	JsonObject json = buildSuccess();
	json.addProperty("token", token);
	// json.addProperty("serverCity", serverCity);
	json.add("collocationData",
		AGsonBuilder.create().toJsonTree(collocationExt));
	return json;
    }

    /**
     * 退出登录
     */
    @Override
    public JsonElement logout(HttpServletRequest request) {
	ApiTokenUtils.setTokenExpiration(request,
		ApiTokenUtils.COLLOCATION_REDIS_PRE_KEY,
		getThreadLocalCollocationId());
	Cookie[] cookies = request.getCookies();// clear all cookie
	if (cookies != null) {
	    for (Cookie cookie : cookies) {
		cookie.setMaxAge(0);
	    }
	}
	JsonObject json = buildSuccess();
	return json;
    }

}
